package com.globefrog.example.consumer.controller;

import com.globefrog.example.client.ProviderClient;
import com.globefrog.example.consumer.vo.ConsumerVo;
import com.globefrog.example.request.ProviderUserRequest;
import com.globefrog.example.request.UserRequest;
import com.globefrog.example.response.UserResponse;
import com.globefrog.framework.web.BaseRestController;
import com.globefrog.framework.web.response.BaseResponse;
import java.time.LocalDateTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : Globe-Frog
 * @date : Create in 2021/7/8
 */
@Slf4j
@RestController
@RequestMapping("/example/consumer")
public class ConsumerController extends BaseRestController {

  @Autowired
  private ProviderClient providerClient;


  /**
   * 根据id获取用户信息
   *
   * @param userId 用户id
   * @return 用户实体
   */
  @GetMapping("/user/{userId}")
  public BaseResponse<UserResponse> getById(@PathVariable("userId") Long userId) {
    UserResponse userResponse = new UserResponse();
    userResponse.setId(userId);
    userResponse.setName("张三疯");
    userResponse.setSex(true);
    userResponse.setCreated(LocalDateTime.now());
    userResponse.setUpdated(LocalDateTime.now());
    return BaseResponse.success(userResponse);
  }


  /**
   * 对于post或者put请求,尽量写全参数，根据不同场景进行适配参数
   *
   * @param request 用户请求
   * @return
   */
  @RequestMapping(
      value = "/user",
      method = RequestMethod.POST,
      consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
      produces = MediaType.APPLICATION_JSON_UTF8_VALUE
  )
  public BaseResponse<Void> save(@RequestBody UserRequest request) {

    // 调用第三方接口
    ProviderUserRequest providerUserRequest = new ProviderUserRequest();
    providerUserRequest.setId(request.getId());
    providerUserRequest.setAge(request.getAge());
    providerUserRequest.setSex(request.getSex());
    // 调用provider接口执行调用
    providerClient.saveUser(providerUserRequest);
    return BaseResponse.success();
  }


  @DeleteMapping("/user/{userId}")
  public BaseResponse<Void> deleteById(@PathVariable("userId") String userId) {
    log.info("删除用户, 用户id={}", userId);
    return BaseResponse.success("删除成功");
  }

  /**
   * 消费信息
   * @return consumer
   */
  @GetMapping
  public ConsumerVo consumer(){
    ConsumerVo consumer = new ConsumerVo();
    consumer.setId("666");
    consumer.setName("ddd");
    consumer.setStatus("success");
    consumer.setOrderId("123456");
    return consumer;
  }
}
